#!/usr/bin/python
# -*- coding: utf-8 -*-


'''
Created on 2013-6-25

@author: lyj
'''


from bsddb import db

import sys, os, time 


# some helpers fcns 


# fork into 2 instances and collide 
pid = os.fork() 


# Create database if there isn't one yet
database = 'mydatabase'
if not os.path.isdir(database):
  os.makedirs(database)

# Part 1: Create database and insert some data
# 
filename = 'fruit' 


# Get an instance of BerkeleyDB 
db_env = db.DBEnv() 
db_env.set_lk_detect(db.DB_LOCK_YOUNGEST) 
db_env.open(database, db.DB_INIT_LOCK
                   | db.DB_CREATE
                   | db.DB_INIT_MPOOL)



# force a collision 
time.sleep(2) 


an_id = db_env.lock_id() 


print pid, an_id 


fruitDB = db.DB(db_env) 
# Create a database in file "fruit" with a Hash access method 
#       There are also, B+tree and Recno access methods 
fruitDB.open(filename, None, db.DB_HASH, db.DB_CREATE) 


# Print version information 
print '\t', pid, db.DB_VERSION_STRING 


while(1): 
    try: 
        lock = db_env.lock_get(an_id, "anytid", db.DB_LOCK_WRITE,
db.DB_LOCK_NOWAIT) 
        break 
    except Exception, error: 
        # print error 
        pass 


print pid, "here" 


# force another one 
time.sleep(2) 


# Insert new elements in database
for k, v in [('apple', 'red'), ('orange', 'orange'), ('banana', 'yellow')]:
    fruitDB[k] = v


db_env.lock_put(lock) 
print pid, "there" 


# Close database 
fruitDB.close() 


# Part 2: Open database and write its contents out 
# 
fruitDB = db.DB(db_env) 
# Open database 
#       Access method: Hash 
#       set isolation level to "dirty read (read uncommited)" 
fruitDB.open(filename, None, db.DB_HASH, db.DB_DIRTY_READ) 


# print database content
for k, v in fruitDB.items():
    print '%s = %s' % (k, v)

fruitDB.close() 
